import { Anchor, message, Spin } from 'antd';
import React, { ReactNode, useEffect, useState } from 'react';
import { ContentItem } from './data';
import styles from './index.less';
import { getContent } from './service';

const { Link } = Anchor;

export default () => {
  const [loading, setLoading] = useState<boolean>(true);

  const [menuItem, setMenuItem] = useState<ReactNode[]>([]);
  const [contentItem, setContentItem] = useState<ReactNode[]>([]);

  const menus: ReactNode[] = [];
  const contents: ReactNode[] = [];

  const contentChildren = (list: ContentItem[], level: number) => {
    if (!list || list.length === 0) return;
    list.forEach((item: ContentItem) => {
      menus.push(
        <Link
          href={`#${item.id}`}
          title={item.name}
          key={`${level}_${item.id}_1`}
          className={styles[`menus_${level}`]}
        />,
      );
      contents.push(
        <div
          id={item.id}
          key={`${level}_${item.id}`}
          dangerouslySetInnerHTML={{ __html: item.namewithstyle }}
        />,
      );
      contents.push(
        <div key={`${level}_${item.id}_3`} dangerouslySetInnerHTML={{ __html: item.content }} />,
      );
      contentChildren(item.childList, level + 1);
    });
  };

  const contentView = async () => {
    const { code, datas, info }: { datas: [] } = await getContent();

    if (code != 0) {
      message.error(info);
      return;
    }

    if (!datas) {
      return;
    }
    contentChildren(datas, 1);
    setLoading(false);
    setMenuItem(menus);
    setContentItem(contents);
  };

  useEffect(() => {
    contentView();
  }, []);

  return (
    <div className={styles.main}>
      {loading ? (
        <div className={styles.center}>
          <Spin spinning={loading} size="large" />
        </div>
      ) : (
        <div className={styles.content}>
          <div className={styles['content-menu']}>
            <Anchor>{menuItem && menuItem.length > 0 && menuItem}</Anchor>
          </div>

          <div className={styles['content-view']}>
            {contentItem && contentItem.length > 0 && contentItem}
          </div>
        </div>
      )}
    </div>
  );
};
